from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import ValidationError

from app.schemas.response import BaseResponse
from app.core.config import settings
from app.db.session import engine, Base
from app.db.init_db import init_db
from app.api.v1.routers import api_router

app = FastAPI(title=settings.PROJECT_NAME)
# 创建数据库表
Base.metadata.create_all(bind=engine)

# 初始化数据库（创建初始 admin 用户）
init_db()

# 包含 API 路由
app.include_router(api_router, prefix="/api/v1")

# 启用 CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 自定义 HTTPException 处理器
@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
    return JSONResponse(
        status_code=exc.status_code,
        content=BaseResponse(code=exc.status_code, message=exc.detail).dict()
    )

# 自定义请求验证错误处理器
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    return JSONResponse(
        status_code=422,
        content=BaseResponse(code=422, message="Validation error", data=exc.errors()).dict()
    )